package com.ziroom.crm.mq.core.validation;

import com.ziroom.crm.mq.core.config.MqConfig;
import com.ziroom.crm.mq.core.init.InitFunc;
import com.ziroom.crm.mq.core.logging.Log;
import com.ziroom.crm.mq.core.logging.LogFactory;
import com.ziroom.crm.mq.core.persistence.Persistence;
import com.ziroom.crm.mq.core.util.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author WeiShaoying
 * @version 1.0
 * @date Created in 2020年09月07日 20:26
 * @since 1.0
 */
public class ValidationInitFunc implements InitFunc {

    private static final Log log = LogFactory.getLog(ValidationInitFunc.class);

    @Override
    public void init() throws Exception {
        checkPersistenceType();
    }

    private void checkPersistenceType() {
        //校验类型
        String persistenceType = MqConfig.getConfig(MqConfig.PERSISTENCE_TYPE);

        if (persistenceType.equals(Persistence.FILE)) {
            String persistenceFilePath = MqConfig.getConfig(MqConfig.PERSISTENCE_FILE_PATH);

            // 判断文件路径是否配置
            if (StringUtils.isNoneBlank(persistenceFilePath)) {
                throw new RuntimeException("持久化文件路径必须配置, [persistenceFilePath]");
            }

            //尝试创建文件
            Path path = Paths.get(persistenceFilePath, "test");
            FileUtils.createIfNoExist(path);
            try {
                Files.delete(path);
            } catch (IOException e) {
                log.error("delete file fail", e);
            }
        }
    }

}
